package com.zx.web.dao.impl;

import com.zx.bean.Goods;
import com.zx.bean.GoodsType;
import com.zx.utils.DataSourceUtils;
import com.zx.web.dao.GoodsDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 章鑫
 * @version V1.0
 * @Project 2022-09-05
 * @Package com.zx.web.dao.impl
 * @Description:
 * @Date 2022/9/14 15:29
 */
public class GoodsDaoImpl implements GoodsDao {
    QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public long findTotalCount(int typeId) {
        String sql = "select count(1) from tb_goods where typeid = ?";
        try {
            return (long) qr.query(sql,new ScalarHandler(),typeId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.println("获取总条数失败");
        }
        return 0;
    }

    @Override
    public List<Goods> findDataPage(int pageNum, int pageSize, int typeId) {
        String sql = "select * from tb_goods where typeid = ? limit ?,? ";
        //(pageNum-1)*pageSize;
        try {
            return qr.query(sql,new BeanListHandler<>(Goods.class),typeId,(pageNum-1)*pageSize,pageSize);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            System.out.println("获取数据失败");
        }
        return null;
    }

    @Override
    public Goods findGoodsDetail(int id) {
        String sql = "select * from tb_goods where id = ?";
        try {
            return qr.query(sql, new BeanHandler<>(Goods.class),id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public GoodsType findGoodsType(int typeid) {
        String sql = "select * from tb_goods_type where id = ?";
        try {
            return qr.query(sql,new BeanHandler<>(GoodsType.class), typeid);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}
